package com.kaifamiao.jsp.servlet;

import com.kaifamiao.utils.JdbcHelper;
import com.kaifamiao.utils.RowHandler;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.logging.Logger;

@WebServlet( "/customer/sign/up" )
public class CustomerSignUpServlet extends HttpServlet {

    private Logger logger = Logger.getLogger( this.getClass().getName() );

    @Override
    protected void doPost(HttpServletRequest request , HttpServletResponse response )
            throws ServletException, IOException {

        final String signUpURL = request.getContextPath() + "/sign-up.jsp" ;
        // 如果校验失败
        if( !this.validate(request) ){
            response.sendRedirect( signUpURL );
            return ;
        }

        String username = request.getParameter( "username" );
        String password = request.getParameter( "password" );
        String nickname = request.getParameter( "nickname" );
        String name = request.getParameter( "name" );
        String gender = request.getParameter( "gender" );
        String birthdate = request.getParameter( "birthdate" );

        java.sql.Date sqlDate = null ;
        DateFormat df = new SimpleDateFormat("yyyy-MM-dd" );
        try {
            java.util.Date utilDate = df.parse( birthdate );
            sqlDate = new java.sql.Date( utilDate.getTime() );
        } catch (ParseException e) {
            e.printStackTrace();
        }

        JdbcHelper helper = JdbcHelper.getInstance();

        Integer id = helper.single("SELECT ifnull(max(id),0) + 1 FROM t_customers", new RowHandler<Integer>() {
            @Override
            public Integer handle(ResultSet rs) throws SQLException {
                return rs.getInt( 1 );
            }
        });

        String sql = "INSERT INTO t_customers " +
                     "( id , username , password , nickname , name , gender , birthdate ) " +
                     "VALUES ( ? , ? , ? , ? , ? , ? , ? )" ;
        Object[] params = { id , username , password , nickname , name , gender , sqlDate };
        int count = helper.execute( sql , params );
        helper.release();
        if( count == 1 ) {
            String url = request.getContextPath() + "/sign-in.jsp" ;
            response.sendRedirect( url );
            return ;
        }

        request.getSession().setAttribute( "message" , "注册失败" );
        response.sendRedirect( signUpURL );
    }

    /**
     * 对请求参数进行数据校验，以确保数据有效
     * @param request 表示请求对象
     * @return 当所有请求参数都通过检验时返回 true
     */
    private boolean validate(HttpServletRequest request) {
        HttpSession session = request.getSession();
        String username = request.getParameter( "username" );
        if( username == null || username.trim().isEmpty() ) {
            session.setAttribute( "message" , "用户名不能为空" );
            return false ;
        }
        String password = request.getParameter( "password" );
        if( password == null || password.trim().isEmpty() ) {
            session.setAttribute( "username" , username );
            session.setAttribute( "message" , "密码不能为空" );
            return false ;
        }
        String confirm = request.getParameter( "confirm" );
        if( !password.equals( confirm )){
            session.setAttribute( "username" , username );
            session.setAttribute( "message" , "两次密码不一致" );
            return false ;
        }
        String nickname = request.getParameter( "nickname" );
        if( nickname == null || nickname.trim().isEmpty() ) {
            session.setAttribute( "username" , username );
            session.setAttribute( "message" , "昵称不能为空" );
            return false ;
        }
        String name = request.getParameter( "name" );
        if( name == null || name.trim().isEmpty() ) {
            session.setAttribute( "username" , username );
            session.setAttribute( "nickname" , nickname );
            session.setAttribute( "message" , "真实姓名不能为空" );
            return false;
        }
        String gender = request.getParameter( "gender" );
        if( gender == null || gender.trim().isEmpty() ) {
            session.setAttribute( "username" , username );
            session.setAttribute( "nickname" , nickname );
            session.setAttribute( "name" , name );
            session.setAttribute( "message" , "请选择性别" );
            return false;
        }
        String birthdate = request.getParameter( "birthdate" );
        if( birthdate == null || birthdate.trim().isEmpty() ) {
            session.setAttribute( "username" , username );
            session.setAttribute( "nickname" , nickname );
            session.setAttribute( "name" , name );
            session.setAttribute( "gender" , gender );
            session.setAttribute( "message" , "请选择出生日期" );
            return false ;
        }

        return true ;
    }
}
